var datatable;// 定义一个全局的dataTable
var data;
var brand_data;
var pgw_data;
var columnJson;
var paramData;
$(function() {
	$('#table tbody').on('click', 'tr', function() {
		if ($(this).hasClass('selected')) {
			$(this).removeClass('selected');
		} else {
			datatable.$('tr.selected').removeClass('selected');
			$(this).addClass('selected');
		}
	});
	init();
	$('input[name="dimType"]').change(function(){
		//维度radiochange事件
		dimOperate();
	});
	showArearList("area");
	
	if($("#jspType").val() == 'kqi_evalution_zczdphTable_more'){
		var timeSize_link = $('#timeSize_link').val();
		$("input[type='radio'][name=timeSize][value='"+timeSize_link+"']").attr("checked",true);
		$("input[type='radio'][name=dimType][value='area']").attr("checked",true);
		$("#area option[value="+$("#city_code_link").val()+"]").attr("selected", true);
		dimOperate();
	}
});
function createColumns(dimType){
	var dynamicColumns=[];
	
	var preStr="<th>时间</th><th>终端厂商</th>";
	var subfix="<th>用户数</th><th>总流量</th><th>上行包</th><th>下行包</th><th>上行流量</th><th>下行流量</th><th>首包延时</th><th>首页延时</th><th>Attach成功率（%）</th><th>会话建立成功率（%）</th><th>TAU成功率（%）</th><th>TCP握手成功率（%）</th><th>DNS解析成功率（%）</th><th>综合下载速率</th>";   
	$("#table thead tr").empty();
	$("#table tbody").empty();
	$("#table thead tr").append(preStr);
	var terminalModelBox_checkbox =$('#terminalModelBox').is(':checked');
	if(terminalModelBox_checkbox){
		//选中终端类型
		$("#table thead tr").append("<th>终端类型</th>");
		dynamicColumns.push({
				data : "terminal_model"
			});
	}
	
	if(dimType==""){
		//没有选维度
	}else{
		if(dimType=="area"){
			$("#table thead tr").append("<th>地市</th>");
			dynamicColumns.push({
					data : "city_code"
				});
			var tacBox =$('#tacBox').is(':checked');
			if(tacBox){
				//tac选中
				$("#table thead tr").append("<th>TAC</th>");
				dynamicColumns.push({
						data : "tac"
					});
			}
			var enodeidbBox =$('#enodeBIDCheckBox').is(':checked');
			if(enodeidbBox){
				//enodeidb选中
				$("#table thead tr").append("<th>eNodeBID</th>");
				dynamicColumns.push({
						data : "enodeb_id"
					});
			}
			var cellNameCheckBox =$('#cellNameCheckBox').is(':checked');
			if(cellNameCheckBox){
				//小区选中
				$("#table thead tr").append("<th>小区名称</th>");
				dynamicColumns.push({
						data : "cell_name"
					});
			}
		}
		if(dimType=="mme"){
			$("#table thead tr").append("<th>MME</th>");
			dynamicColumns.push({
					data : "drive_name",
				});
		}
	}
	$("#table thead tr").append(subfix);
//	var ht=$("#table thead tr").html();
//	alert(ht);
	var preColumns=[
					{
						data : "report_date"
					},
					{
						data : "terminal_brand",
						render:function(value,type,row){
							var brandName='';
			            	for(var j=0;j<brand_data.length;j++){
			            		var tempValue=brand_data[j].value;
			            		if(null!=value&&value!=undefined)
			            			value=value.trim();
			            		if(tempValue==value){
			            			brandName=brand_data[j].label;
			            			break;
			            		}
			            	}
							return brandName;
						}
					} 
					];
	var subColumns=[{
						data : "user_count"
					},
					{
						data : "flow_total"
					} ,
					{
						data : "up_packet"
					} ,
					{
						data : "down_packet"
					} ,
					{
						data : "flow_up"
					} ,
					{
						data : "flow_down"
					} ,
					{
						data : "first_packet_time"
					} ,
					{
						data : "first_page_time"
					} ,
					{
						data : "attach_success_rate",
						render : function(value, type, row) {
							//var url="../../businessAnalysis/tcp/index?";
							var hrefStr ="<a href='#' onclick=linkToAttach()  >"+row.attach_success_rate+"</a>";
			            	return hrefStr;
						}
					} ,
					{
						data : "session_success_rate",
						render : function(value, type, row) {
							//var url="../../businessAnalysis/tcp/index?";
							var hrefStr ="<a href='#' onclick=linkToSession()  >"+row.session_success_rate+"</a>";
			            	return hrefStr;
						}
					} ,
					{
						data : "tau_success_rate",
						render : function(value, type, row) {
							//var url="../../businessAnalysis/tcp/index?";
							var hrefStr ="<a href='#' onclick=linkToTAU()  >"+row.tau_success_rate+"</a>";
			            	return hrefStr;
						}
					} ,
					{
						data : "tcp_success_rate",
						render : function(value, type, row) {
							//var url="../../businessAnalysis/tcp/index?";
							var hrefStr ="<a href='#' onclick=linkToTCP()  >"+row.tcp_success_rate+"</a>";
			            	return hrefStr;
						}
					} ,
					{
						data : "dns_success_rate",
						render : function(value, type, row) {
							//var url="../../businessAnalysis/tcp/index?";
							var hrefStr ="<a href='#' onclick=linkToDNS()  >"+row.dns_success_rate+"</a>";
			            	return hrefStr;
						}
					} ,
					{
						data : "speed"
					}  
					];
	var columns= preColumns.concat(dynamicColumns).concat(subColumns);   
	return columns;
	
}
function getList(){
	var timeSize = $('input:radio[name="timeSize"]:checked').val();
	var terminalCheck=false,tacCheck=false,eNodeBIDCheck=false,cellNameCheck=false,mmeCheck=false,areaCheck=false;
	var tacCheck=0
	var beginDate = $("#beginDate").val();
	var endDate = $("#endDate").val();
	if(beginDate==""){
		alert("请选择开始时间！");
		return;
	}
	if(endDate==""){
		alert("请选择结束时间！");
		return;
	}
	
	var beginDate1 = new Date(beginDate.replace(/-/g,"/"));
	var endDate2 = new Date(endDate.replace(/-/g,"/"));
	if((beginDate1-endDate2)>0){
		alert("开始时间不能大于或等于结束时间！");
		return;
	}
	var driveId="";
	var terminalBrand=$("#brandDiv").val();
	var terminalModel="";
	var terminalModelBox_checkbox =$('#terminalModelBox').is(':checked');
	if(terminalModelBox_checkbox){
		terminalCheck=true;
		terminalModel=$("#modelDiv").val();
		if(terminalModel=="全部"){
			terminalModel="";//当没有点击品牌的时候，型号没有值，所以值会是全部
		}
	}
	var tac="";
	var eNodeBID="";
	var cellName="";
	var city_code="";
	var dimType = $('input:radio[name="dimType"]:checked').val();
	if(null==dimType || dimType==undefined){
		dimType="";
		driveId="";
	}else{
		if(dimType=="area"){
			areaCheck=true;
			city_code=$("#area").val().trim();
			var tacBox =$('#tacBox').is(':checked');
			var enodeidbBox =$('#enodeBIDCheckBox').is(':checked');
			var cellNameCheckBox =$('#cellNameCheckBox').is(':checked');
			if(tacBox){
				tacCheck=true;
				tac=$("#tac_input").val().trim();
			}
			if(enodeidbBox){
				eNodeBIDCheck=true;
				eNodeBID=$("#enodeidBID_input").val().trim();
			}
			if(cellNameCheckBox){
				cellNameCheck=true;
				cellName=$("#cellName_input").val().trim();
			}
			city_code=$("#area").val().trim();
		}
		if(dimType=="mme"){
			mmeCheck=true;
			driveId=$("#pgwDiv").val();		
		}
	}
	

	//$("#table tbody tr").remove();
	$("#tbodyId").remove();
	$('#table').append($("<tbody id='tbodyId'></tbody>"));
	if (datatable == undefined || datatable == "undefined" || datatable == null) {
	} else {
		datatable.fnDestroy();
	}
	
	var columns=createColumns(dimType);
	columnJson=dealColumnJson(columns);
	datatable = $('#table')
			.dataTable(
					{
						"aoColumnDefs" : [ {
							sDefaultContent : '',
							aTargets : [ '_all' ]
						} ],
						"bPaginate" : true, // 翻页功能
						"bLengthChange" : false, // 改变每页显示数据数量
						"bFilter" : false, // 过滤功能
						"bSort" : true, // 排序功能
						"bInfo" : true,// 页脚信息
						"bAutoWidth" : true,// 自动宽度
						// "sPaginationType": "full_numbers",//显示分页的样式
						// 还有simple_numbers等
//						"sScrollX" : "100%",
						"sScrollXInner" : "110%",
						"bScrollCollapse" : true,
						"iDisplayLength" : 50,
						"oLanguage" : {
							"sLengthMenu" : "每页显示 _MENU_条",
							"sZeroRecords" : "没有找到符合条件的数据",
							"sProcessing" : "&nbsp;&nbsp;&nbsp;&nbsp;查询中，请稍等...",
							"sInfo" : "当前第 _START_ - _END_ 条　共计 _TOTAL_ 条",
							"sInfoEmpty" : "没有记录",
							"sInfoFiltered" : "(从 _MAX_ 条记录中过滤)",
							"sSearch" : "搜索：",
							"oPaginate" : {
								"sFirst" : "首页",
								"sPrevious" : "前一页",
								"sNext" : "后一页",
								"sLast" : "尾页"
							}
						},
						"bProcessing" : true,
						"bServerSide" : true,
						"sAjaxSource" : "../../businessAnalysis/terminalPerformance/getList",
						"fnServerData" : function(sSource, aoData, fnCallback) {
							paramData={
									"aoData" : JSON.stringify(aoData),
									"timeSize":timeSize,
									"beginDate" : beginDate,
									"endDate" : endDate,
									"driveId" : driveId,
									"terminalBrand" : terminalBrand,
									"terminalModel" : terminalModel,
									"tac" : tac,
									"eNodeBID" : eNodeBID,
									"cellName" : cellName,
									"cityCode" : city_code,
									"terminalCheck" : terminalCheck,
									"tacCheck" : tacCheck,
									"eNodeBIDCheck" : eNodeBIDCheck,
									"cellNameCheck" : cellNameCheck,
									"areaCheck":areaCheck,
									"mmeCheck" : mmeCheck
									
								};
							$.ajax({
										"type" : "post",
										"contentType" : "application/x-www-form-urlencoded",
										"url" : sSource,
										"dataType" : "json",
										"data" : paramData, // 以json格式传递
										"success" : function(resp) {
											fnCallback(resp.pageDate);
											data = resp.allData;
										}
									});
						},
						columns :columns

					});
}
function removeColumns(con){
	var flag=false;
	for(var k=0;k<columns.length;k++){
		var obj=columns[k];
		if(obj.dynamic==true){
			flag=true;
			break;
		}
	}
	if(flag){
		for(var l=0;l<con;l++){
			columns.pop();
		}
	}
	
}
function dimOperate(){
	 var dimType=$('input[name="dimType"]:checked ').val();
	 if(dimType=="area"){
		 $(".dimmme").hide();
	 }
	 if(dimType=="mme"){
		 $(".dimarea").hide();
	 }
	 $(".dim"+dimType).show();
}
function init(){
	//
	/*if(paramFlag == 'false'){
			$("input:radio[name='dimType'][value='"+paramDimType+"']").eq(0).attr("checked",'checked');
			dimOperate();
			getList();
	}*/
	$(".dimmme").hide();
	$(".dimarea").hide();
	$("#pgwDiv").jqxComboBox({promptText: "全部",width: 230,height: 25});
	$("#brandDiv").jqxComboBox({promptText: "全部",width: 230,height: 25});
	$("#modelDiv").jqxComboBox({promptText: "全部",width: 230,height: 25});
		    $("#brandDiv").val("");
		    var brandsource =
		    {
		        datatype: "json",
		        datafields: [
		            { name: 'value' },
		            { name: 'label' }
		        ],
		        url: "../../businessAnalysis/terminalPerformance/getBrandList",
		        async: false
		    };
		    brand_data=new Array() ; 
		    var brandAdapter = new $.jqx.dataAdapter(brandsource);

		    $("#brandDiv").jqxComboBox(
		    { 
		    	source: brandAdapter, 
		    	promptText: "全部",
		    	displayMember: "value", 
		    	valueMember: "label", 
		    	width: 230, 
		    	height: 25,
		    	autoComplete: true,
		    	renderer: function (index, label, value) {
		    		
	                var item = brandAdapter.records[index];
	                
	                if (item != null) {

	                    var label = item.label ;
	                    brand_data[index]=item;
	                    return label;

	                }
	                	return "";


	            }
		    });
		    $("#brandDiv").val("all");
		    $("#brandDiv").on('change', function (event) {
		    	getModelList($(this).val());
		    });
		    pgw_data=new Array() ;
			  var pgwsource =
			    {
			        datatype: "json",
			        datafields: [
			            { name: 'drive_id' },
			            { name: 'drive_name' }
			        ],
			        url: "../../businessAnalysis/terminalPerformance/getDriveList",
			        async: false
			    };
			    var pgwAdapter = new $.jqx.dataAdapter(pgwsource);

			    // 网元
			    $("#pgwDiv").jqxComboBox(
			    { 
			    	source: pgwAdapter, 
			    	promptText: "全部",
			    	displayMember: "drive_name", 
			    	valueMember: "drive_id", 
			    	width: 230, 
			    	height: 25,
			    	autoComplete: true,
			    	renderer: function (index, label, value) {
			    		
		                var item = pgwAdapter.records[index];
		                
		                if (item != null) {

		                    var label = item.drive_name ;
		                    pgw_data[index]=item;
		                    return label;

		                }
		                	return "";


		            }
			    });
			    $("#pgwDiv").val("");
}

function getModelList(brandId){
	var modelsource =
    {
        datatype: "json",
        datafields: [
            { name: 'terminal_model' },
            { name: 'terminal_model' }
        ],
        url: "../../businessAnalysis/terminalPerformance/getModelList?brandId="+brandId,
        async: false
    };
	var modelAdapter = new $.jqx.dataAdapter(modelsource);

    // 信令类型名称
    $("#modelDiv").jqxComboBox(
    { 
    	source: modelAdapter, 
    	promptText: "全部",
    	displayMember: "terminal_model", 
    	valueMember: "terminal_model", 
    	width: 230, 
    	height: 25,
    	autoComplete: true
    });
}
//下拉树 begin
function onClick(e, treeId, treeNode) {
	var zTree = $.fn.zTree.getZTreeObj("treeDemo"),
	nodes = zTree.getSelectedNodes(),
	v = "";
	nodes.sort(function compare(a,b){return a.id-b.id;});
	for (var i=0, l=nodes.length; i<l; i++) {
		v += nodes[i].name + ",";
	}
	if (v.length > 0 ) v = v.substring(0, v.length-1);
	var cityObj = $("#citySel");
	cityObj.attr("value", v);
	$("#area").val(treeNode.id);
	
	hideMenu();
}
/**
 * 显示树
 */
function showMenu() {
	var cityObj = $("#citySel");
	var cityOffset = $("#citySel").offset();
	$("#menuContent").css({left:cityOffset.left-26 + "px", top:cityOffset.top-206 + "px"}).slideDown("fast");

	$("body").bind("mousedown", onBodyDown);
}
/**
 * 隐藏树
 */
function hideMenu() {
	$("#menuContent").fadeOut("fast");
	$("body").unbind("mousedown", onBodyDown);
}
function onBodyDown(event) {
	if (!(event.target.id == "menuBtn" || event.target.id == "menuContent" || $(event.target).parents("#menuContent").length>0)) {
		hideMenu();
	}
}

function exportExcel() {
	if(paramData==undefined ||paramData==null ||paramData==''){
		alert("请先点击查询，然后导出！");
		return;
	}
	var countRecord = $("#table tbody tr :not(.dataTables_empty)").length;//总行数  
	if(countRecord==0){
		alert("没有可导出符合条件的的数据！");
		return;
	}
	paramData["columnJson"]=JSON.stringify(columnJson);
	$.ajax({
		type : "POST",
		url : "../../businessAnalysis/terminalPerformance/exportExcel?rand="
				+ Math.random(),
		dataType : "json",
		"data" : paramData,
		success : function(data) {
			if (data.flag) {
				var url = "../../businessAnalysis/terminalPerformance/downFiles?path="
						+ data.path;
				window.location.href = url;
			} else {
				alert(data.msgs);
			}
		}
	});
}
function dealColumnJson(columns){
	
	columnJson=[];
	for(var i=0;i<columns.length;i++){
		var key=columns[i].data;
		$("#table thead tr th").each(function (index){
			var text="";
			if(index==i){
				text=$(this).text().trim();
				var jsonObj={ "key" : key.trim(),         "text" : text.trim()};
				columnJson.push(jsonObj);
			}
		});
	}
	return columnJson;
}
/**
 * 跳转TCP
 */
function linkToTCP(){
	var url="/businessAnalysis/tcp/index?";
	linkTab("TCP建立性能分析",url);
}
/**
 * 跳转附着
 */
function linkToAttach(){
	var url="/businessAnalysis/attachment/index?";
	linkTab("附着质量指标",url);
}
/**
 * 跳转session
 */
function linkToSession(){
	var url="/businessAnalysis/session/sessioncreateanalysis?";
	linkTab("会话建立分析",url);
}
/**
 * 跳转DNS
 */
function linkToDNS(){
	var url="/businessAnalysis/dns/index?";
	linkTab("DNS指标",url);
}
/**
 * 跳转TAU
 */
function linkToTAU(){
	var url="/businessAnalysis/tui/index?";
	linkTab("跟踪区更新分析",url);
	
}